﻿using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;

namespace SendEmailConsoleApplication1
{
    public class SMTPEmailSender
    {
        //If your smtp server wants authentication,use it 
        public SMTPEmailSender(String smtpServer, String user, String password)
        {
            mailMessage = new MailMessage();
            smtpClient = new SmtpClient();
            smtpClient.Host = smtpServer;
            smtpClient.Port = 25;
            smtpClient.Credentials = new NetworkCredential(user, password);
        }

        //If your smtp server doesn't want authentication,use it 
        public SMTPEmailSender(String smtpServer)
        {
            mailMessage = new MailMessage();
            smtpClient = new SmtpClient(smtpServer);
        }

        public String Subject
        {
            get
            {
                return mailMessage.Subject;
            }

            set
            {
                mailMessage.Subject = value;
            }
        }

        //get/set the email's content
        public String Content
        {
            get
            {
                return mailMessage.Body;
            }
            set
            {
                mailMessage.Body = value;
            }
        }

        public String From
        {
            get
            {
                return mailMessage.From.Address;
            }

            set
            {
                mailMessage.From = new MailAddress(value);
            }
        }

        public void AddReceiver(String email)
        {
            mailMessage.To.Add(email);
        }

        public void Send()
        {
            smtpClient.Send(mailMessage);
        }

        public void AddAttachment(String filepath, string name = "")
        {
            var a = new Attachment(filepath);
            if (!string.IsNullOrEmpty(name))
            {
                a.Name = name;
            }
            else
            {
                a.Name = Path.GetFileName(filepath);
            }
            mailMessage.Attachments.Add(a);
        }

        public void AddAttachment(Stream contentStream, string name, string contentType)
        {
            mailMessage.Attachments.Add(new Attachment(contentStream, name, contentType));
        }
        public void AddAttachment(Stream contentStream, ContentType contentType)
        {
            mailMessage.Attachments.Add(new Attachment(contentStream, contentType));
        }
        private MailMessage mailMessage;
        private SmtpClient smtpClient;
    }
}